using System.ComponentModel;
using System.Configuration;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraLayout;
using RedRiver.Framework.XtraCommon.Templates;

namespace RedRiver.Framework.XtraCommon.UserAuthentication{
    public partial class AppSettingsForm : XtraDialogForm{
        public AppSettingsForm(){
            InitializeComponent();
        }

        public void BindingSettings(ApplicationSettingsBase settings){
            ((ISupportInitialize) (defaultBindingSource)).BeginInit();
            defaultBindingSource.AllowNew = false;
            defaultBindingSource.DataSource = settings.GetType();

            dataLayoutControl.BeginInit();
            foreach (SettingsProperty property in settings.Properties){
                var edit = new TextEdit();
                edit.Name = property.Name + "TextEdit";
                edit.DataBindings.Add(new Binding("EditValue", defaultBindingSource, property.Name, true));
                dataLayoutControl.Controls.Add(edit);
                var layout = new LayoutControlItem(layoutControlGroup1);
                layout.Name = "ItemFor" + property.Name;
                layout.Control = edit;
                layout.CustomizationFormText = GetPropertyName(property);
                layout.Text = layout.CustomizationFormText;
                dataLayoutControl.Root.AddItem(layout);
            }
            dataLayoutControl.DataSource = defaultBindingSource;
            dataLayoutControl.EndInit();
            ((ISupportInitialize) (defaultBindingSource)).EndInit();
            defaultBindingSource.DataSource = settings;
        }

        private static string GetPropertyName(SettingsProperty property){
            if (property.Attributes.ContainsKey(typeof (DisplayNameAttribute))){
                return ((DisplayNameAttribute) property.Attributes[typeof (DisplayNameAttribute)]).DisplayName;
            }
            return property.Name;
        }
    }
}